package com.boot.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

//@Configuration
public class SentinelConfig {

    @PostConstruct  // 在Bean初始化后执行
    public void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();

        // Warm Up 规则（订单接口预热）
        FlowRule warmUpRule = new FlowRule("GET:/order/create")
                .setGrade(RuleConstant.FLOW_GRADE_QPS)
                .setCount(1000)  // 最终阈值
                .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP)
                .setWarmUpPeriodSec(10);  // 10秒预热

        // 匀速排队规则（支付接口限流）
        FlowRule rateLimitRule = new FlowRule("POST:/order/pay")
                .setGrade(RuleConstant.FLOW_GRADE_QPS)
                .setCount(100)   // 恒定QPS
                .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
                .setMaxQueueingTimeMs(2000);  // 最大排队2秒

        rules.add(warmUpRule);
        rules.add(rateLimitRule);

        FlowRuleManager.loadRules(rules);  // 加载规则
    }
}